$(document).ready(function(){
    if($('form#cvForm').length > 0){
        getIndexes();
    }
    $('#add-language').on('click',function(){
        $(this).parent().find('.controls:last').removeClass('alert alert-info').trigger('blur');
        $(this).before('<div class="controls alert alert-info added">' +
                            '<input type="text" id="languages_'+indexes.language+'" name="languages['+indexes.language+'].name" placeholder="Language">' +
                            '<select id="lang-select" name="languages['+indexes.language+'].level" data-other="'+indexes.language+'">' +
                                '<option>Beginner</option> ' +
                                '<option>Intermediate</option> ' +
                                '<option>Advanced</option> ' +
                                '<option value="other">Other..</option>' +
                            '</select> ' +
                            '<div class="move-arrows"><span class="arrow-up icon-circle-arrow-up"></span><span class="arrow-down icon-circle-arrow-down"></span></div>'+
                        '</div>');
        $('select[data-other="'+indexes.language+'"]').otherSelect();
        $('#languages_'+indexes.language).focus();
        indexes.language +=1;
    });
    $('#add-skill').on('click',function(){
        $(this).parent().find('.controls:last').removeClass('alert alert-info').trigger('blur');
        $(this).before('<div class="controls alert alert-info added">' +
                            '<input type="text" id="skills_'+indexes.skill+'" name="skills['+indexes.skill+'].name" placeholder="Skill">' +
                            '<select id="skill-select" name="skills['+indexes.skill+'].level" data-other="'+indexes.skill+'">' +
                                '<option>Beginner</option> ' +
                                '<option>Intermediate</option> ' +
                                '<option>Advanced</option> ' +
                                '<option value="other">Other..</option>' +
                            '</select> ' +
                            '<div class="move-arrows"><span class="arrow-up icon-circle-arrow-up"></span><span class="arrow-down icon-circle-arrow-down"></span></div>'+
                        '</div>');
        $('select[data-other="'+indexes.skill+'"]').otherSelect();
        $('#skills_'+indexes.skill).focus();
        indexes.skill += 1;
    });
    $('#add-experience').on('click', function(){
        $(this).parent().find('.controls:last').removeClass('alert alert-info').trigger('blur');
        $(this).before(' <div class="controls alert alert-info span8 added">'+
                            '<div class="span8">'+
                                '<div class="span3"><label>Employer </label><input type="text" class="employer" id="employer_'+indexes.experience+'" name="experiences['+indexes.experience+'].employer" placeholder="Employer"></div>'+
                                '<div class="span2"><label>Start Date </label>'+
                                    '<div class="input-append date exp-datepicker startDate" id="startDate_'+indexes.experience+'" data-date="12-02-2012" data-date-format="dd-mm-yyyy">'+
                                        '<input class="span2" size="16" type="text" value="12-02-2012" name="experiences['+indexes.experience+'].fromDate" readonly>'+
                                        '<span class="add-on"><i class="icon-th"></i></span>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="span2"><label>End Date </label>'+
                                    '<div class="input-append date exp-datepicker endDate" id="endDate_'+indexes.experience+'" data-date="12-02-2012" data-date-format="dd-mm-yyyy">'+
                                        '<input class="span2" size="16" type="text" value="12-02-2012" name="experiences['+indexes.experience+'].toDate" readonly>'+
                                        '<span class="add-on"><i class="icon-th"></i></span>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="span3"><label>Position </label><input type="text" class="position" id="position_'+indexes.experience+'" name="experiences['+indexes.experience+'].position" placeholder="Position"></div>'+
                                '<div class="span8"><label>Description</label><textarea rows="4" class="span8 description" id="description_'+indexes.experience+'" name="experiences['+indexes.experience+'].description" placeholder="Description"></textarea></div>'+
                            '</div>'+
                            '<div class="move-arrows"><span class="arrow-up icon-circle-arrow-up"></span><span class="arrow-down icon-circle-arrow-down"></span></div>'+
                            '<hr class="span8" style="margin-left:0px">'+
                        '</div><br>');
        $('#employer_'+indexes.experience).focus();
        indexes.experience +=1;
    });

    //plugins
    $('#dp3').datepicker();
    $('#dp6').datepicker();
    $('.exp-datepicker').datepicker();
    $('#lang-select').otherSelect();
    $('#skill-select').otherSelect();

    //events
    $(".skill:last").addClass("last");
    $('.content-section').on('blur','.controls.added',function(){
        $(this).removeClass('alert alert-info');
        if($(this).find('button.remove').length == 0){
            var exp = $(this).find('hr');
            if(exp.length > 0){
                exp.before('<button class="remove btn btn-danger" type="button"><span class="icon-remove icon-white"></span> Remove</button> ');
            }else{
                $(this).append('<button class="remove btn btn-danger" type="button"><span class="icon-remove icon-white"></span> Remove</button> ');
            }
        }
    });

    $('.content-section').on('click', '.remove', function(){
        var container = $(this).parent().parent();
        $(this).parent().remove();
        reindex(container);
    });

    //events for moving inputs up and down
    //could be better written
    $('.content-section').on('mouseover','.move-arrows', function(){
        $(this).fadeTo('slow',1);
    });
    $('.content-section').on('mouseleave','.move-arrows', function(){
         $(this).fadeTo('slow',0);
    });
    $('.content-section').on('click','.arrow-up', function(){
        var parent = $(this).parent().parent('.controls'),
            prevControls = parent.prevAll('.controls').first();
        if($(prevControls).length > 0){
            $(prevControls).before(parent);
            reindex(parent.parents('.control-group'));
        }
        return false;
    });
    $('.content-section').on('click','.arrow-down', function(){
        var parent = $(this).parent().parent('.controls'),
            nextControls = parent.nextAll('.controls').first();
        if($(nextControls).length > 0){
            $(nextControls).after(parent);
            reindex(parent.parents('.control-group'));
        }
        return false;
    });
    $(".component-parent-class").each(function(i) {
        var $this = $(this);
        $this.parents(".content-section:first").addClass($this.val());
    });
    $(".search-form").attr('action', $(".search-form-address:first").val());
});
var indexes = {
    language : 1,
    skill : 1,
    experience : 1
};

//get input indexes
function getIndexes (){
    indexes.language = parseInt($('#lang-group .controls').last().find('input').attr('id').split('_')[1]) + 1;
    indexes.skill = parseInt($('#skill-group .controls').last().find('input').attr('id').split('_')[1]) + 1;
    indexes.experience = parseInt($('#experience-group .controls').last().find('input.employer').attr('id').split('_')[1]) + 1;
}

//reindex inputs afer delete
function reindex(container){
    var groupId = container.attr('id'),
        addedControls = container.find('.controls.added'),
        index = 0;
    if(groupId == 'lang-group'){
        for(i = 0, len = addedControls.length; i < len ; i++){
            index = i + 1;
            $(addedControls[i]).find('input').attr('id','languages_'+index ).attr('name','languages['+ index +'].name');
            $(addedControls[i]).find('select').attr('name','languages['+ index +'].level').attr('data-other', index);
            indexes.language = index;
        }
    }else if(groupId == 'skill-group'){
        for(i = 0, len = addedControls.length; i < len ; i++){
            index = i + 1;
            $(addedControls[i]).find('input').attr('id','skills_'+index ).attr('name','skills['+ index +'].name');
            $(addedControls[i]).find('select').attr('name','skills['+ index +'].level').attr('data-other', index);
            indexes.skill = index;
        }
    }else if(groupId == 'experience-group'){
        for(i = 0, len = addedControls.length; i < len ; i++){
            index = i + 1;
            $(addedControls[i]).find('input.employer').attr('name','experiences['+ index +'].employer').attr('id','employer_['+ index +']' );
            $(addedControls[i]).find('.startDate input').attr('name','experiences['+ index +'].fromDate');
            $(addedControls[i]).find('.startDate').attr('id','startDate_['+ index +']');
            $(addedControls[i]).find('.endDate input').attr('name','experiences['+ index +'].toDate');
            $(addedControls[i]).find('.endDate').attr('id','endDate_['+ index +']');
            $(addedControls[i]).find('input.position').attr('name','experiences['+ index +'].position').attr('id','position_['+ index +']' );
            $(addedControls[i]).find('textarea.description').attr('name','experiences['+ index +'].description').attr('id','description_['+ index +']' );
            indexes.experience = index;
        }
    }
}

//plugin for adding other options in select boxes
(function ($){

    $.fn.otherSelect = function(){

        var uniqueId = $(this).attr('id')+'-'+$(this).attr('data-other'),
            input = '<input class="span2" id="addOption" data-otherSelect = "'+uniqueId+'" type="text" name="addOption" >',
            option = '<option class="added" data-otherOption= "'+uniqueId+'" selected></option>';

        this.on('change',function(){
            if($(this).find('option:selected').val() == 'other'){
                $(this).after(input);
                $(this).append(option);
                var newOption = $(this).find('option.added[data-otherOption='+uniqueId+']');
                $('input[data-otherSelect='+uniqueId+']').on('keyup', function(){
                    newOption.text($(this).val());
                });
                $('input[data-otherSelect='+uniqueId+']').on('blur',function(){
                    newOption.removeClass('added');
                    $(this).remove();
                });
            }
        });
    }

})( jQuery );

